<script lang="ts" setup>
  import { computed, ref } from 'vue'

  import { requestUpdateDetectionInfo } from '@/api/business/tracecode/detectionInfo'
  import BottomButton from '@/components/BottomButton/BottomButton.vue'
  import { HttpCodeEnum } from '@/enum/httpEnum'
  import { commonPng } from '@/enum/imageEnum'
  import { scanTypeDesc } from '@/enum/statusResultsEnum'
  import env from '@/env/index'
  import { useUserInfoStore } from '@/stores/userInfo'
  import { getToken } from '@/utils/storage'
  const userInfoStore = useUserInfoStore()
  import Layout from './components/Layout.vue'
  import Progress from './components/Progress.vue'
  const props = defineProps<{ detectionInfoId: string }>()
  const latitude = ref(0) // 腾讯地图经纬度
  const longitude = ref(0)
  const lat = ref('') // 经纬度转换为度分秒格式
  const lng = ref('')
  const initMap = ref(false)
  const address = ref('')
  const photo = ref('')
  wx.authorize({
    scope: 'scope.userFuzzyLocation',
    success() {
      getFuzzyLocation()
    },
  })
  wx.authorize({
    scope: 'scope.camera',
    success() {},
  })
  const getFuzzyLocation = () => {
    wx.getFuzzyLocation({
      type: 'wgs84', // 返回 gps 坐标
      success(res) {
        latitude.value = res.latitude
        longitude.value = res.longitude
        initMap.value = true
        getAddress()
      },
    })
  }
  function getDecimalPart(number: number) {
    return number % 1
  }
  const getAddress = () => {
    wx.request({
      url: `https://apis.map.qq.com//ws/geocoder/v1?location=${latitude.value},${longitude.value}&key=IC6BZ-NIT6B-5RGUE-NDJ46-O4S73-OPFZ6`,
      data: {
        x: '',
        y: '',
      },
      header: {
        'content-type': 'application/json', // 默认值
      },
      success(res: any) {
        const { result } = res.data || {}
        address.value = result.address
        // 1、经纬度的整数部分是度分秒中的度。
        // 2、经纬度的小数部分×60得到的整数部分就是度分秒中的分。
        // 3、再用2经纬度的小数部分×60，得到的就是度分秒中的秒。
        // 纬度 >= 0 为北纬
        // 经度 >= 0 为东纬
        let latDu = Math.floor(result.location.lat)
        let latDecimalPart = getDecimalPart(result.location.lat)
        let latFen = Math.floor(latDecimalPart * 60)
        let latMiao = latFen * 60

        let lngDu = Math.floor(result.location.lng)
        let lngDecimalPart = getDecimalPart(result.location.lng)
        let lngFen = Math.floor(lngDecimalPart * 60)
        let lngMiao = lngFen * 60

        lat.value = `${latDu}°${latFen}′${latMiao}″${latDu >= 0 ? 'E' : 'W'}`
        lng.value = `${lngDu}°${lngFen}′${lngMiao}″${lngDu >= 0 ? 'N' : 'S'}`
        console.log('逆地址解析: ', result)
      },
    })
  }
  const repositioning = () => {
    address.value = ''
    latitude.value = 0
    longitude.value = 0
    lat.value = ''
    lng.value = ''
    wx.getSetting({
      success(res: any) {
        if (res.authSetting['scope.userFuzzyLocation']) {
          getFuzzyLocation()
        } else {
          wx.showToast({
            title: '请先开启位置权限',
            icon: 'none',
            duration: 2000,
          })
        }
      },
    })
  }
  const takePhoto = () => {
    wx.getSetting({
      success(res: any) {
        if (res.authSetting['scope.camera']) {
          photo.value = ''
          wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['camera'],
            maxDuration: 30,
            camera: 'back',
            success(res: any) {
              photo.value = res.tempFiles[0].tempFilePath
              uploadFile()
            },
          })
        } else {
          wx.showToast({
            title: '请先开启摄像头权限',
            icon: 'none',
            duration: 2000,
          })
        }
      },
    })
  }
  const takeNewPhoto = () => {
    takePhoto()
  }
  const error = (e: any) => {
    console.log(e.detail)
  }
  const nextOpacity = computed(() => {
    if (!lat.value || !photo.value) {
      return 0.5
    }
    return 1
  })
  const uploadFile = () => {
    wx.showLoading({
      title: '图片上传中',
    })
    console.log('start uploadFile: ', photo.value)
    wx.uploadFile({
      url: `${env.api}/contentFile/upload/V1`,
      filePath: photo.value,
      name: 'file',
      header: { Authorization: getToken() },
      success(res: any) {
        const data = JSON.parse(res.data)
        if (data.responseCode === HttpCodeEnum.SUCCESS) {
          console.log('uploadFile success: ', res)
          photo.value = data.responseData
        } else {
          uni.showToast({ title: data.responseMessage || '上传图片失败', icon: 'none' })
        }
      },
      fail(err) {
        console.log('uploadFile fail: ', err)
      },
      complete() {
        wx.hideLoading()
      },
    })
  }
  const updateDetectionInfo = async () => {
    wx.showLoading({
      title: '正在提交',
    })
    const { responseCode, responseMessage } = await requestUpdateDetectionInfo({
      detectionInfoId: props.detectionInfoId,
      photoUrl: photo.value,
      location: address.value,
      coordinates: `${lat.value} ${lng.value}`,
      status: 20,
      detectionType: userInfoStore.detectionType,
    })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      console.log('UpdateDetectionInfo success: ', responseMessage)
      if (userInfoStore.detectionType === 2) {
        uni.switchTab({
          url: `/pages/tabbar/microbiota`,
        })
        return
      }
      uni.navigateTo({
        url: `/pages/detection/collectSamples?detectionInfoId=${props.detectionInfoId}`,
      })
    } else {
      console.log('UpdateDetectionInfo faild: ', responseCode, responseMessage)
      uni.showToast({ title: responseMessage || '更新检测信息失败', icon: 'none', duration: 3000 })
    }
    wx.hideLoading()
  }
  const nextStep = async () => {
    if (nextOpacity.value === 0.5) {
      return
    }
    updateDetectionInfo()
  }
</script>

<template>
  <Layout :title="scanTypeDesc[userInfoStore.detectionType]" :is-scroll="true">
    <template #progress> <Progress :type="userInfoStore.detectionType" step="2" name="位置认证" /></template>
    <template #content>
      <view class="correct-positioning" @click="repositioning">
        定位有误？点我
        <image class="position-refresh" :src="commonPng.refresh" />
      </view>
      <view class="map-content" v-if="initMap">
        <map id="map" class="map" :show-location="true" :latitude="latitude" :longitude="longitude"></map>
      </view>
      <view class="position-info">
        <view class="position-info-item">
          <text class="item-name">位置</text>
          <text class="item-vlaue">{{ address }}</text>
        </view>
        <view class="position-info-item">
          <text class="item-name">坐标</text>
          <text class="item-vlaue">{{ lat }} {{ lng }}</text>
        </view>
      </view>
      <view v-if="photo" class="photo">
        <image :src="photo" mode="widthFix" />
      </view>
      <view v-if="photo" class="new-photo" @click="takeNewPhoto">重拍一张</view>
      <view v-else class="take-photos" @click="takePhoto">拍照存证</view>
    </template>
    <template #button>
      <view class="photo-hint">请拍摄所在地的标志性建筑或者大门，用于证明所在位置。</view>
      <view :style="{ opacity: nextOpacity }">
        <BottomButton buttonText="下一步" @on-click="nextStep()" :is-pre="false" />
      </view>
    </template>
  </Layout>
</template>

<style lang="less" scoped>
  :deep(.content) {
    margin-top: 48rpx !important;
  }

  .correct-positioning {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 32rpx;
    font-size: 32rpx;
    font-weight: 500;
    color: #08979c;

    .position-refresh {
      width: 40rpx;
      height: 40rpx;
      margin-left: 16rpx;
    }
  }

  .map-content {
    flex: 1;
    width: 100%;
    border-radius: 32rpx;

    .map {
      flex: 1;
      width: 100%;
      border-radius: 32rpx;
    }
  }

  .position-info {
    padding: 32rpx;
    margin: 16rpx 0 32rpx;
    background: #f7f8fa;
    border-radius: 32rpx;

    .position-info-item {
      font-size: 28rpx;

      &:not(:nth-last-of-type(1)) {
        margin-bottom: 32rpx;
      }

      .item-name {
        color: #4e5969;

        &::before {
          display: inline-block;
          width: 16rpx;
          height: 16rpx;
          margin-right: 16rpx;
          content: ' ';
          background: #ff9d3e;
          border-radius: 50%;
        }
      }

      &:nth-last-of-type(1) .item-name {
        &::before {
          background: #13c2c2;
        }
      }

      .item-vlaue {
        margin-left: 32rpx;
        color: #1d2129;
      }
    }
  }

  .photo,
  .camera {
    margin-bottom: 32rpx;
  }

  .camera {
    width: 100%;
  }

  .new-photo,
  .take-photos {
    font-size: 32rpx;
    font-weight: 500;
    color: #08979c;
    text-align: center;
  }

  .take-photos {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 88rpx;
    border: 1px solid #08979c;
    border-radius: 44rpx;
  }

  .photo-hint {
    padding: 32rpx 64rpx;
    font-size: 16px;
    line-height: 24px;
    color: #4e5969;
  }
</style>
